package net.sureon.web;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sureon.app.AppContext;
import net.sureon.app.UserSession;
import net.sureon.biz.CompanyBO;
import net.sureon.biz.CompanyMgr;
import net.sureon.biz.GroupBO;
import net.sureon.biz.GroupMgr;
import net.sureon.biz.TitaonMailHelper;
import net.sureon.biz.UserBO;
import net.sureon.biz.UserMgr;
import net.sureon.common.mail.MailData;
import net.sureon.common.mail.MailProcessor;
import net.sureon.common.security.Role;
import net.sureon.common.security.SecurityUtils;
import net.sureon.dao.Company;
import net.sureon.dao.Group;
import net.sureon.dao.User;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class RegisterCompany implements Controller {

	private CompanyMgr companyMgr;
	private GroupMgr groupMgr;
	private UserMgr userMgr;

	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String saveCompanyForm = request.getParameter("saveCompanyForm");
		// 判断用户是提交请求还是修改
		String submitStatus = request.getParameter("submitStatus");
		if ("true".equals(saveCompanyForm)) {
			// 表示用户填写符合要求，成功进入下一步
			
			// 判断用户的siteURL是否已经被注册过，如果是的，则提示出错信息

			String siteURL = request.getParameter("siteURL");
			String email = request.getParameter("adminEmail");
			CompanyBO companyBO = null;
			UserBO userBO = null;        //判断Email是否已经被注册过
			try {
				companyBO = companyMgr.getCompany(siteURL);
			}
			catch(Exception e) {
				e.printStackTrace();
			}
			if(companyBO != null) {
				// 表示该siteURL已经被注册过,提示出错信息
				
				request.setAttribute("siteURLHasRegisted", "true");
				return new ModelAndView("registerCompany");
			}
			try {
				userBO = userMgr.getUserByEmail(email);
			} catch(Exception e) {
				
			}
			if(userBO != null) {
				request.setAttribute("emailHasRegisted", "true");
				return new ModelAndView("registerCompany");
			}
			CompanyForm companyForm = new CompanyForm();
			companyForm.setAdminName(request.getParameter("adminName"));
			companyForm.setAdminEmail(request.getParameter("adminEmail"));
			// 联系人职位
			companyForm.setAdminTitle(request.getParameter("adminTitle"));

			companyForm.setCompanyFullName(request
					.getParameter("companyFullName"));
			
			companyForm.setCompanyWebSite(request.getParameter("companyWebSite"));
			
			companyForm.setSiteURL(request.getParameter("siteURL"));
			companyForm.setCompanyZipCode(request
					.getParameter("companyZipcode"));
			
			companyForm.setAdminPassword(request.getParameter("adminPassword"));
			
			String companyAddress = request.getParameter("address");
			String adminFax = request.getParameter("adminFax1") + "-"
					+ request.getParameter("adminFax2");

			String adminTel = request.getParameter("adminTel1") + "-"
					+ request.getParameter("adminTel2");

			String adminTel1 = request.getParameter("adminTel1");
			String adminTel2 = request.getParameter("adminTel2");
			String adminFax1 = request.getParameter("adminFax1");
			String adminFax2 = request.getParameter("adminFax2");
			
			companyForm.setAdminTel1(adminTel1);
			companyForm.setAdminTel2(adminTel2);
			companyForm.setAdminFax1(adminFax1);
			companyForm.setAdminFax2(adminFax2);
			
			companyForm.setCompanyAddress(companyAddress);
			companyForm.setAdminFax(adminFax);
			companyForm.setAdminTel(adminTel);

			request.getSession().setAttribute("companyForm", companyForm);
			return new ModelAndView("comfirmRegisterCompany");
		}
		
		if("modify".equals(submitStatus)) {
			// 修改请求信息
//			response.sendRedirect("");
//			return null;
		}
		
		if ("确定".equals(submitStatus)) {
			// 进行注册公司

			Company company = new Company();
			company.setAdminName(request.getParameter("adminName"));
			company.setCompanyAddress(request.getParameter("companyAddress"));
			company.setAdminEmail(request.getParameter("adminEmail"));
			company.setAdminFax(request.getParameter("adminFax"));
			company.setAdminTel(request.getParameter("adminTel"));
			company.setCompanyFullName(request.getParameter("companyFullName"));
			company.setCompanyZipCode(request.getParameter("companyZipCode"));
			company.setSiteURL(request.getParameter("siteURL"));

			company.setCompanyWebSite(request.getParameter("companyWebSite"));
			company.setAdminTitle(request.getParameter("adminTitle"));
			company.setCompanyStatus("trial_in_now");
			company.setRegisterDate(new Date());
			Calendar cal = Calendar.getInstance();
			cal.roll(Calendar.MONTH, 1);
			cal.roll(Calendar.DATE, 15);
			company.setValidDate(cal.getTime());

			CompanyBO companyBO = new CompanyBO(company);
			long companyID = companyMgr.insertCompany(companyBO);
			if (companyID > 0) {
				// 注册成功！
				// 添加 Group
				String groupName = request.getParameter("siteURL");
				String groupType = "Company";
				Group groupVO = new Group();
				groupVO.setCompanyID(companyID);
				groupVO.setGroupName(groupName);
				groupVO.setGroupType(groupType);
				GroupBO groupBO = new GroupBO(groupVO);
				long groupID = groupMgr.insertGroup(groupBO);
				if (groupID > 0) {
					// 表示组创建成功
					// 添加groupManager
					User user = new User();
					user.setCompanyID(companyID);
					user.setGroupID(groupID);
					user.setSalt("randomsalt");
					user.setUserName(request.getParameter("adminEmail"));
					user.setTitle(request.getParameter("adminTitle"));
					user.setRealName(request.getParameter("adminName"));
					String password = SecurityUtils.generateSHA512Hash(user
							.getSalt()
							+ ":" + request.getParameter("adminPassword"));
					user.setPassword(password);
					user.setRegisterDate(new java.util.Date());
					user.setRole(Role.ROLE_NAME_COMPAYADMIN);
					user.setEmail(request.getParameter("adminEmail"));
					UserBO userBO = new UserBO(user);
					userBO.activateUser();

					long userID = userMgr.insertUser(userBO);

					if (userID > 0) {
						// 表示人创建成功
						// 更新UserGroup表，是这个人成为改组的groupManager
						groupBO.getGroupVO().setGroupManager(userID);
						long updateRows = groupMgr.updateGroup(groupBO);
						if (updateRows > 0) {
							String initPassword = request
									.getParameter("adminPassword");
							String mailName = TitaonMailHelper.MAIL_NAME_COMPANY_ACCOUT_OPEND;
							
							AppContext.setCurrentUserSession(new UserSession(userBO));

							// 更新成功！发mail通知用户
							Map replacementMap = TitaonMailHelper.getInstance()
									.generateCompanyMacro(companyBO);
							replacementMap.putAll(TitaonMailHelper
									.getInstance().generateUserMacro(userBO));
							if (initPassword != null) {
								replacementMap.put(
										TitaonMailHelper.MACRO_INIT_PASSWORD,
										initPassword);
							}
							if (companyBO.getCompanyVO().getValidDate() != null) {
								replacementMap
										.put(
												TitaonMailHelper.MACRO_COMPAY_VALID_DATE,
												companyBO.getCompanyVO()
														.getValidDate());
							}
							MailData data = MailData.defaulMailData();
							data.setReplacementMap(replacementMap);
							data.setRecipients(new String[] { userBO
									.getUserVO().getEmail() });
							MailProcessor.getInstance().processMail(mailName,
									data, mailName, AppContext.getLocale());

							//  去除session中的值
							request.getSession().removeAttribute("companyForm");
							response.sendRedirect(request.getContextPath()
									+ "/index.do?registerCompany=success");
							return null;
						}
					}
				}

				request.getSession().removeAttribute("companyForm");
				response.sendRedirect(request.getContextPath() + "/index.do");
			} else {
				// 注册失败
				System.out.println("注册失败！");
			}

		}

		return new ModelAndView("registerCompany");
	}

	public CompanyMgr getCompanyMgr() {
		return companyMgr;
	}

	public void setCompanyMgr(CompanyMgr companyMgr) {
		this.companyMgr = companyMgr;
	}

	public GroupMgr getGroupMgr() {
		return groupMgr;
	}

	public void setGroupMgr(GroupMgr groupMgr) {
		this.groupMgr = groupMgr;
	}

	public UserMgr getUserMgr() {
		return userMgr;
	}

	public void setUserMgr(UserMgr userMgr) {
		this.userMgr = userMgr;
	}

}